<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');

$daytime = time();
$condition = array(
	'team_type' => 'normal',
	'city_id' => array(0, abs(intval($city['id']))),
	"begin_time <= '{$daytime}'",
);

if (!option_yes('displayfailure')) {
	$condition['OR'] = array(
		"now_number >= min_number",
		//"end_time > '{$daytime}'",
	);
}

$count = Table::Count('team', $condition);
list($pagesize, $offset, $pagestring) = pagestring($count, 10);
$teams = DB::LimitQuery('team', array(
	'condition' => $condition,
	'order' => 'ORDER BY begin_time DESC, id DESC',
	'size' => $pagesize,
	'offset' => $offset,
));
foreach($teams AS $id=>$one){
	team_state($one);
	if ($one['state']=='none') $one['picclass'] = 'isopen';
	if ($one['state']=='soldout') $one['picclass'] = 'soldout';
	
	/* get partner info */
	$one['partner'] = Table::Fetch('partner', $one['partner_id']);
	/* End */
	
	/* get tatics */
	$min_discount = 10;
	$max_discount = 0;
	$tatics = explode('|', $one['tatics']);
	foreach($tatics as $sid=>$t){
		$tatics[$sid] = explode(',', $t);
		$discountTmp = explode('-', $tatics[$sid][2]);
		if(($user_network_weights['total'] >= $tatics[$sid][0])){
			if($tatics[$sid][1] == 0){
				$one['discount_rate'] = $tatics[$sid][2];
			} elseif($user_network_weights['total'] < $tatics[$sid][1]){
				if($user_network_weights['total'] == 0){
					$one['discount_rate'] = $discountTmp[1];
				} else{
					// 低折扣+（高折扣-低折扣）/（高影响力-低影响力）*（个人影响力-低影响力）
					$one['discount_rate'] = round($discountTmp[0] + (($discountTmp[1] - $discountTmp[0])/($tatics[$sid][1] - $tatics[$sid][0]))*($user_network_weights['total'] - $tatics[$sid][0]), 1);
				}
			}
		}
		if($min_discount > $discountTmp[0]){
			$min_discount = $discountTmp[0];
		}
		if($max_discount < $discountTmp[1]){
			$max_discount = $discountTmp[1];
		}
	}
	$one['min_discount'] = $min_discount;
	$one['max_discount'] = $max_discount;
	/* End */
	
	$teams[$id] = $one;
}

$pagetitle = '特惠地图';

include template('team_index');
